package com.boonya.lab.rpc.server;

import com.boonya.protobuf.grpc.WebSiteGrpc;
import com.boonya.protobuf.grpc.WebSiteDefinition;
import io.grpc.stub.StreamObserver;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.server.service.GrpcService;
import org.springframework.stereotype.Service;

import java.util.Hashtable;
import java.util.Map;

/**
 * @author Pengjunlin
 * @date 2024/12/27
 */
@GrpcService
@Slf4j
@Service
public class WebSiteServiceGrpcImpl extends WebSiteGrpc.WebSiteImplBase {

    private static final Map<String, Object> websiteMap = new Hashtable<>();

    static {
        websiteMap.put("china", "www.baidu.com");
        websiteMap.put("usa", "www.google.com");
    }

    @Override
    public void getHttpWebsite(WebSiteDefinition.AreaReq request, StreamObserver<WebSiteDefinition.HttpWebsiteResp> responseObserver) {
        if (websiteMap.containsKey(request.getAreaCode())) {
            String httpUrl = websiteMap.getOrDefault(request.getAreaCode(), "Unknown").toString();
            if ("Unknown".equals(httpUrl)) {
                // 如果没有找到对应的区域代码，可以返回一个错误响应或者空响应
                responseObserver.onCompleted();
                return;
            }
            // 创建响应对象
            WebSiteDefinition.HttpWebsiteResp response = WebSiteDefinition.HttpWebsiteResp.newBuilder()
                    .setCode(200)
                    .setMessage("获取" + request.getAreaCode() + "地址")
                    .setData(httpUrl)
                    .build();
            // 发送响应
            responseObserver.onNext(response);
            // 完成RPC调用
            responseObserver.onCompleted();
        }
    }
}
